package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.constant.MallResultCode;
import club.kynb.mall.application.context.MallUserContext;
import club.kynb.mall.application.context.OrderSubmitContext;
import club.kynb.mall.application.model.model.command.SubmitOrderCommand;
import club.kynb.mall.user.api.IShippingAddressService;
import club.kynb.mall.user.model.dto.ShippingAddressDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.Optional;


/**
 * @author kynb_club@163.com
 * @since 2021/7/7 1:56 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class CheckShippingAddressFilter extends AbstractSubmitOrderFlowFilter {
    private final IShippingAddressService iShippingAddressService;

    @Override
    protected void doService(OrderSubmitContext orderSubmitContext) {
        final MallUserContext mallUserContext = MallUserContext.get(true);
        final Long userId = mallUserContext.getUserDTO().getId();
        final SubmitOrderCommand command = orderSubmitContext.getCommand();
        final Optional<ShippingAddressDTO> optional = iShippingAddressService.getById(command.getShippingAddressId());
        final ShippingAddressDTO shippingAddressDTO = optional.orElseThrow(() -> Errors.BIZ.exception(MallResultCode.CODE_13002));
        Checker.ifNotThrow(shippingAddressDTO.getUserId().equals(userId), () -> Errors.BIZ.exception("传入非当前用户的收货地址"));
        orderSubmitContext.setShippingAddress(shippingAddressDTO);
    }
}
